<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" :rules="rules">
         <!-- 日期 -->
         <el-form-item label="时间" label-width="40px">
            <WeekTimePicker type="datetime" v-model="queryParams.startTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px"/>
            <span style="margin: 0px 6px;">~</span>
            <WeekTimePicker type="datetime" v-model="queryParams.endTime" format="yyyy-MM-dd HH:mm" :clearable="false" style="width: 160px" />
         </el-form-item>
         <!-- 制造区域 -->
         <el-form-item label="制造区域" prop="factoryAreaId">
            <el-select v-model="queryParams.factoryAreaId" placeholder="区域" style="width: 80px">
               <el-option
                  v-for="dict in factoryAreaIdOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
               />
            </el-select>
         </el-form-item>
         <!-- 制造类型 -->
         <el-form-item label="制造类型" prop="productionTypeId">
            <el-select v-model="queryParams.productionTypeId" placeholder="制造类型" @change="productionTypeIdChange" style="width: 100px">
               <el-option
                        v-for="dict in listProductionTypeOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
               />
            </el-select>
         </el-form-item>

         <!-- 父设备 -->
         <el-form-item label="设备ID" prop="topId">
            <el-select v-model="queryParams.topId" multiple
                                collapse-tags
                                collapse-tags-tooltip placeholder="设备ID" style="width: 160px">
               <el-option
                        v-for="dict in topIdOptions"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
               />
            </el-select>
         </el-form-item>

      </el-form>

      <el-row :gutter="0" class="mb8" style="height: 20px;">
      <el-radio-group v-model="queryParams.radioVal" @change="radioChange" style="margin-bottom: 10px;">
        <el-radio-button label="全部履历"></el-radio-button>
        <el-radio-button label="故障(Down)"></el-radio-button>
        <el-radio-button label="保养(PM)"></el-radio-button>
        <el-radio-button label="待机(IDLE)"></el-radio-button>
        <el-radio-button label="离线(OFF)"></el-radio-button>
      </el-radio-group>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getTableData">
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getTableData">搜索</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
        </el-form-item>
      </right-toolbar>
    </el-row>

      <t-ag-grid
          v-loading="loading"
          style="height: calc(100% - 65px);"
          :column-defs="column"
          :row-data="tableData"
          :row-buffer="20"
          :tooltipShowDelay="0"
          align="center"
          :defaultColDef = "{
              // suppressMenu:true
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          header-align="center"
          />
   </div>
</template>
<script setup name="OeeTimeHistory">
  import moment from 'moment'
  import { getModelType } from '@/common/affect'
  import { queryTableData, allColumn, downColumn, getTopId, getSon } from './config'

  const queryParams = reactive({
    startTime: moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00'),
    endTime: moment().format('YYYY-MM-DD 08:30:00'),
    factoryAreaId: '层前',
    productionTypeId: '叠瓦',
    topId: null,
    machineIdList: null,
    radioVal: '全部履历'
  })

  const rules = {
    factoryAreaId: [{ required: true, message: "制造区域不能为空", trigger: "change" }],
    productionTypeId: [{ required: true, message: "制造类型不能为空", trigger: "change" }],
    topId: [{ required: true, message: "父设备不能为空", trigger: "input" }]
  }

  const total = ref(0)
  const radioVal = ref('全部履历')
  const column = ref([])
  const tableData = ref([])
  column.value = allColumn

  const factoryAreaIdOptions = ref([])
  const listProductionTypeOptions = ref([])
  const topIdOptions = ref([])
  const machineIdListOptions = ref([])

  const loading = ref(false)
  const showSearch = ref(true)

  const { proxy } = getCurrentInstance()

  onActivated(() => {
    let state = history?.state
    if(state?.factoryAreaId && state?.productionTypeId && state?.topId && state?.startTime&& state?.endTime){
      getTopId({
        machineType: state.productionTypeId
      }).then((res) => {
        queryParams.topId = null
        queryParams.machineIdList = null
        topIdOptions.value = []
        machineIdListOptions.value = []
        res.rows.forEach(item => {
          topIdOptions.value.push({
            label: item,
            value: item
          })
        })

        queryParams.startTime = state.startTime
        queryParams.endTime = state.endTime
        queryParams.factoryAreaId = state.factoryAreaId
        queryParams.productionTypeId = state.productionTypeId
        queryParams.topId = state.topId

        getTableData()
      })
    }

    // 指标分析
    if(state?.startTime && state?.endTime && state?.productionTypeId && state?.topId && state?.radioVal){
      getTopId({
        machineType: state?.productionTypeId
      }).then((res) => {
        // queryParams.topId = null
        // queryParams.machineIdList = null
        topIdOptions.value = []
        machineIdListOptions.value = []
        res.rows.forEach(item => {
          topIdOptions.value.push({
            label: item,
            value: item
          })
        })
      })

      queryParams.topId = state?.topId

      queryParams.productionTypeId = state?.productionTypeId
      queryParams.startTime = state?.startTime
      queryParams.endTime = state?.endTime
      queryParams.radioVal = state?.radioVal

      getTableData()
    }
  })

  const productionTypeIdChange = (val) => {
    getTopId({
      machineType: val
    }).then((res) => {
      queryParams.topId = null
      queryParams.machineIdList = null
      topIdOptions.value = []
      machineIdListOptions.value = []
      res.rows.forEach(item => {
        topIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const _tempObj = {
    "全部履历": 'ALL',
    "故障(Down)": 'DOWN',
    "保养(PM)": 'PM',
    "待机(IDLE)": 'IDLE',
    "离线(OFF)": 'OFF'
  }

  const getTableData = () => {
    proxy.$refs.queryRef.validate(valid => {
      if(valid){
        if(moment(queryParams.endTime).subtract(16, 'days') > moment(queryParams.startTime)){
          proxy.$modal.alertWarning('最多查询16天的数据')
          return
        }

        if(moment(queryParams.endTime).unix() > moment(moment().subtract(1, 'days').format('YYYY-MM-DD 08:30:00')).unix()
          && moment().unix() < moment(moment().format('YYYY-MM-DD 10:30:00')).unix()
          || moment(queryParams.endTime).unix() > moment(moment().format('YYYY-MM-DD 08:30:00')).unix()){
          proxy.$modal.alertError('1、系统当日OEE履历不可以查询 <br/>2、系统前日OEE履历须在上午10:30以后查询')
          return
        }
        loading.value = true
        queryTableData({
          startTime: moment(queryParams.startTime).format('YYYY-MM-DD HH:mm:ss'),
          endTime: moment(queryParams.endTime).format('YYYY-MM-DD HH:mm:ss'),
          topIdList: queryParams.topId.join(),
          status: _tempObj[queryParams.radioVal]
        }).then((res) => {
          loading.value = false
          // tableData.value = res.rows[0].oeeMachineWorkList
          tableData.value = []
          res.rows[0].oeeMachineWorkList.forEach((item) => {
            item.keepTime = Number(item.keepTime)
            item.reactTime = Number(item.reactTime)
            item.totalTime = Number(item.totalTime)
            item.totalReactTime = Number(item.totalReactTime)
            tableData.value.push(item)
          })
          total.value = res.rows[0].oeeMachineWorkList.length
        })
      }

    })
  }

  const radioChange = (val) => {
    if(val === '故障(Down)') {
      column.value = downColumn
    } else {
      column.value = allColumn
    }
    getTableData()
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy.download('timeAnalysis/continous/exportAll', {
      startTime: moment(queryParams.startTime).format('YYYY-MM-DD HH:mm:ss'),
      endTime: moment(queryParams.endTime).format('YYYY-MM-DD HH:mm:ss'),
      topIdList: queryParams.topId.join(),
      status: _tempObj[queryParams.radioVal]
    }, `OEE时间履历_${new Date().getTime()}.xlsx`)
  }

  onMounted(() => {
    getModelType({
      factoryAreaIdList: '层前'
    }).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })

    getTopId({
      machineType: '叠瓦'
    }).then((res) => {
      res.rows.forEach(item => {
        topIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  })
</script>